<template>
    <div class="app-container">
        <el-row :gutter="0">
            <!--专病数据-->
            <el-form class="formBox searchForm" :model="queryParams" ref="queryForm" size="small" :inline="true"
                v-show="showSearch" label-width="68px">
                <!-- <el-form-item label="医院" prop="hospital" clearable>
                    <department :isHospital="true" :isdepat="true" @refreshData="refreshData" deptWidth="200px"
                        ref="department"></department>
                </el-form-item> -->
                <el-form-item label="指标名称" prop="detectionName">
                    <el-input v-model="queryParams.detectionName" placeholder="请输入检测指标名称" clearable style="width:200px"
                        @keyup.enter.native="handleQuery" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>

            <div class="formBox searchForm" ref="statisticalTable" style="margin-bottom:0px!important;">
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5" v-if="isAdmin || isPlatform">
                        <!--                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"-->
                        <!--                            v-hasPermi="['system:detection:add']">新增</el-button>-->
                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
                    </el-col>

                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>

                <el-table v-loading="loading" :data="classifyList" border :height="statisticalTableH" ref="table">
                    <!--                <el-table-column type="selection" width="50" align="center" />-->
                    <el-table-column sortable label="指标编号" align="center" prop="detectionId" width="100" />
                    <el-table-column label="控件类型" align="center" prop="detectionType" :show-overflow-tooltip="true"
                        width="100">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.sys_detection_type" :value="scope.row.detectionType" />
                        </template>
                    </el-table-column>
                    <el-table-column sortable label="指标名称" align="center" prop="detectionName" :show-overflow-tooltip="true"
                        width="100" />
                    <!-- <el-table-column label="医院" align="center" prop="hospitalName" :show-overflow-tooltip="true"
                        width="150">
                        <template slot-scope="scope">
                            <departTag :options="deptNameLists" :value="scope.row.hospitalId" />
                        </template>
                    </el-table-column>
                    <el-table-column label="科室" align="center" prop="deptName" :show-overflow-tooltip="true" width="150">
                        <template slot-scope="scope">
                            <departTag :options="deptNameLists" :value="scope.row.deptId" />
                        </template>
                    </el-table-column> -->
                    <el-table-column label="单位" align="center" prop="detectionUnit" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <span v-if="scope.row.detectionUnit">{{ scope.row.detectionUnit }}</span>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="选项值" align="center" prop="defaultValue" :show-overflow-tooltip="true"
                        width="150">
                        <template slot-scope="scope">
                            <span v-if="scope.row.detectionType == '1' && scope.row.valueStr">{{ scope.row.valueStr
                            }}</span>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="默认显示值" align="center" prop="defaultValue" :show-overflow-tooltip="true"
                        width="150" />
                    <el-table-column label="正常值范围" align="center" prop="diseaseSerialization" :show-overflow-tooltip="true"
                        width="150">
                        <template slot-scope="scope">
                            <span v-if="scope.row.detectionType == '0'">{{ scope.row.limitValue }} ~
                                {{ scope.row.hightValue }}</span>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column sortable label="创建时间" align="center" prop="createTime" width="160">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column sortable label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />

                    <!--                    <el-table-column label="操作" align="center" fixed="right" width="160"-->
                    <!--                        class-name="small-padding fixed-width">-->
                    <!--                        <template slot-scope="scope">-->
                    <!--                            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"-->
                    <!--                                v-hasPermi="['system:detection:edit']">修改</el-button>-->
                    <!--                            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"-->
                    <!--                                v-hasPermi="['system:detection:remove']">删除</el-button>-->
                    <!--                        </template>-->
                    <!--                    </el-table-column>-->
                    <el-table-column label="操作" align="center" fixed="right" width="160"
                        class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                                v-if="isAdmin">修改</el-button>
                            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                                v-if="isPlatform" :disabled="(scope.row.hospitalId != hospital.deptId)">修改</el-button>
                            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                                v-if="isAdmin">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />
            </div>

        </el-row>

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :before-close="cancel"
            :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left" class="formBox1">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="指标名称" prop="detectionName" label-width="100px">
                            <el-input v-model="form.detectionName" placeholder="请输入检测指标名称" clearable style="width:450px" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="使用科室" prop="deptId" v-if="open" label-width="100px">
                            <department :isAdd="true" @changedepatData="changedepatData" :HospitalId="form.hospitalId"
                                :Optiohospitals="true" :deptIds="form.deptId" :isdisabled="false" deptWidth="450px">
                            </department>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="控件类型" label-width="100px">
                            <el-radio-group v-model="form.detectionType" :disabled="form.detectionId ? true : false">
                                <el-radio v-for="dict in dict.type.sys_detection_type" :key="dict.value"
                                    :label="dict.value">{{ dict.label }}</el-radio>

                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row v-if="form.detectionType == '0'">
                    <el-col :span="12">
                        <el-form-item label="单位" label-width="100px" prop="detectionUnit">
                            <el-input v-model="form.detectionUnit" placeholder="请输入单位" style="width:250px"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12" v-if="form.detectionType == '0'">
                        <el-form-item label="默认显示值" label-width="100px" prop="defaultValue">
                            <el-input v-model="form.defaultValue" placeholder="请输入默认显示值" style="width:250px"
                                type="number"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12" v-if="form.detectionType == '1'">
                        <el-form-item label="默认显示值" label-width="100px" prop="defaultValue">
                            <el-input v-model="form.defaultValue" placeholder="请输入默认显示值" style="width:250px"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="form.detectionType == '0'">
                    <el-col :span="12">
                        <el-form-item label="高限值" label-width="100px" prop="hightValue">
                            <el-input v-model="form.hightValue" placeholder="请输入高限值" style="width:250px"
                                type="number"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="form.detectionType == '0'">
                    <el-col :span="12">
                        <el-form-item label="低限值" label-width="100px" prop="limitValue">
                            <el-input v-model="form.limitValue" placeholder="请输入低限值" style="width:250px"
                                type="number"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row v-if="form.detectionType == '1'">
                    <el-form-item label="选项值" label-width="100px">
                        <el-tag :key="tag" v-for="tag in form.valueList" closable :disable-transitions="false"
                            @close="handleClose(tag)">
                            {{ tag }}
                        </el-tag>
                        <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput"
                            size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput">+</el-button>
                    </el-form-item>
                </el-row>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="submitForm">提 交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>


    </div>
</template>

<script>
import { mapGetters } from "vuex";
import department from "@/views/components/department/index.vue";
import departTag from "@/views/components/department/departTag.vue";
import { deptNameList } from "@/api/system/dept";
import { listDetection, getDetection, delDetection, addDetection, updateDetection } from "@/api/system/detection";
import { getToken } from "@/utils/auth";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
    name: "detectionList",
    dicts: ["sys_detection_type"],
    components: { department, departTag },
    data() {
        return {
            statisticalTableH: undefined,
            // 遮罩层
            loading: true,
            // 选中数组

            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 专病表格数据
            classifyList: null,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 是否修改
            inputDisabled: false,
            // 表单参数
            // form: {},
            form: {
                detectionName: undefined,
                detectionType: "0",//0文本、 1下拉框
                detectionUnit: '',//单位
                defaultValue: '',//默认值
                hightValue: '',//高限值
                limitValue: '',//低限值
                valueList: [],//选项值 数组 前端用 1 下拉框
                valueStr: '',//选项值 后端 传存 逗号隔开 1 下拉框
                hospitalId: undefined,
                deptId: undefined,
            },
            inputVisible: false,
            inputValue: '',
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                detectionName: undefined,
                hospitalId: undefined,
                deptId: undefined,
            },
            deptNameLists: [],
            // 表单校验
            rules: {
                detectionName: [
                    {
                        required: true,
                        message: "检测指标名称不能为空",
                        trigger: "blur",
                    },
                ],
                deptId: [
                    {
                        required: true,
                        message: "科室必选",
                        trigger: "blur",
                    },
                ],
                // detectionUnit: [
                //     {
                //         required: true,
                //         message: "单位不能为空",
                //         trigger: "blur",
                //     },
                // ],
                // defaultValue: [
                //     {
                //         required: true,
                //         message: "数值不能为空",
                //     }
                // ],
                // hightValue: [
                //     {
                //         required: true,
                //         message: "数值不能为空",
                //     }
                // ],
                // limitValue: [
                //     {
                //         required: true,
                //         message: "数值不能为空",
                //     }
                // ]

            },
            //是否数组



        };
    },
    watch: {
        showSearch() {
            this.$nextTick(() => {
                this.changeHeight()
            }, 1000)

        }
    },
    created() {
        this.getdeptNameList();
        this.loading = false;
    },
    mounted() {
        this.changeHeight()
    },
    computed: {
        ...mapGetters(["isPlatform", "deptId", "hospital"]),
        isAdmin() {
            return this.$store.state.user.name === 'admin' ? true : false
        }
    },
    updated() {
        this.$nextTick(() => {
            this.$refs.table.doLayout()
        })
    },
    methods: {
        changeHeight() {
            if (this.$refs.statisticalTable) {
                const statisticalTableObj = this.$refs.statisticalTable.getBoundingClientRect();
                let h = statisticalTableObj.top + 100
                this.statisticalTableH = 'calc(100vh - ' + h + 'px)'
            } else {
                this.statisticalTableH = '500px'
            }
        },
        refreshData(data) {
            this.queryParams.pageNum = 1;
            this.queryParams.hospitalId = data.hospitalId
            this.queryParams.deptId = data.deptId
            this.getdeptNameList();
        },
        changedepatData(data) {
            if (data && data.length > 0) {
                this.form.deptId = data[0].deptId
                this.form.hospitalId = data[0].parentId == 100 ? data[0].deptId : data[0].parentId
            } else {
                this.form.deptId = undefined
                this.form.hospitalId = undefined
            }
        },
        // 回显医院及门诊
        getdeptNameList() {
            deptNameList().then((response) => {
                this.deptNameLists = response.data;
                this.getList();
            });
        },
        handleClose(tag) {
            console.log(tag)
            this.form.valueList.splice(this.form.valueList.indexOf(tag), 1);
        },
        showInput() {
            this.inputVisible = true;
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        handleInputConfirm() {
            let inputValue = this.inputValue;
            console.log()
            if (inputValue) {
                if (this.form.valueList.indexOf(inputValue) == -1) {
                    this.form.valueList.push(inputValue);
                } else {
                    this.$message({
                        message: '选项值已存在!',
                        type: 'warning'
                    });
                    return false
                }

            }
            this.inputVisible = false;
            this.inputValue = '';
        },
        /** 查询列表 */
        getList() {
            this.loading = true;
            listDetection(
                this.queryParams
            ).then((response) => {
                this.classifyList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            if (this.$refs.department) {
                this.$refs.department.reset()
            }
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.form = {
                detectionName: undefined,
                hospitalId: undefined,
                deptId: undefined,
                detectionType: "0",//0文本、 1下拉框
                detectionUnit: '',//单位
                defaultValue: '',//默认值
                hightValue: '',//高限值
                limitValue: '',//低限值
                valueList: [],//选项值 数组 前端用 1 下拉框
                valueStr: '',//选项值 后端 传存 逗号隔开 1 下拉框
            },
                this.inputDisabled = false
            this.open = true;
            this.title = "新增检测指标";
            this.form.valueList = []
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.inputDisabled = true
            console.log('handleUpdate', row)
            const detectionId = row.detectionId;
            getDetection(detectionId).then((response) => {
                let data = response.data;
                data.valueList = data.valueStr.split(',')
                // this.form.valueStr=this.form.valueList.join(',')
                this.form = data;
                this.open = true;
                this.title = "修改检测指标";
            });
        },

        /** 提交按钮 */
        submitForm: function () {
            if (this.form.detectionType == "1") {
                console.log(this.form.valueList)
                if (this.form.valueList.length == 0) {
                    this.$message({
                        message: '请添加选项值!',
                        type: 'warning'
                    });
                    return false
                } else {
                    this.form.valueStr = this.form.valueList.join(',')
                }
            } else {
                if (this.form.hightValue && this.form.limitValue) {
                    if (Number(this.form.hightValue) < Number(this.form.limitValue)) {
                        this.$message({
                            message: '高限值不能小于低限值!',
                            type: 'warning'
                        });
                        return false
                    }
                }


            }

            let params = this.form
            delete params.valueList
            this.$refs["form"].validate((valid) => {
                console.log(valid)
                if (valid) {
                    console.log("dahh")
                    if (this.form.detectionId != undefined) {
                        updateDetection(params).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;

                            this.getList();
                        });
                    } else {
                        addDetection(params).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;

                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const detectionName = row.detectionName
            const detectionId = row.detectionId
            this.$modal
                .confirm(
                    '是否确认删除指标名称为"' +
                    detectionName +
                    '"的数据项？'
                )
                .then(function () {
                    return delDetection(detectionId);
                })
                .then((res) => {
                    this.getList();
                    if (res.code == 200) {
                        this.$modal.msgSuccess("删除成功");
                    }
                })
                .catch(() => { });
        },
    },
};
</script>
<style scoped>
.el-tag {
    margin-right: 15px;
}

.el-tag+.el-tag {
    margin-left: 10px;
}

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>
